//
//  RegionViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/28.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "RegionViewController.h"
#import "define.h"
#import "AsyncConnection.h"
#import "UIImageView+WebCache.h"
#import "NomalPullLayout.h"
#import "ImageColl.h"
#import "SpecailWebViewController.h"
#import "UIButton+WebCache.h"
#import "MJRefresh.h"

int k = 18;
@interface RegionViewController ()< UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *topArr;
@property (nonatomic, assign) CGFloat offHeigt;
@property (nonatomic, assign) CGFloat offWidth;


@end

@implementation RegionViewController

- (void)dealloc
{
    [_collection release];
    [_table release];
    [_array release];
    [_topArr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self topConnection];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.offHeigt = [[UIScreen mainScreen]bounds].size.height / 667;
    self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
    
    self.navigationItem.title = self.name;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    // Do any additional setup after loading the view.
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)beginConnection
{
    
    NSDictionary *dic = @{@"asc":@"",
                          @"flag":@"",
                          @"id":self.kid,
                          @"sort":@"all",
                          @"query":self.name,
                          @"cat":@"全部",
                          @"asc":@""};
    [AsyncConnection asyncConnection:REGION_KOREAN parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *a = [[dic objectForKey:@"data"]objectForKey:@"items"];
        [self.array addObjectsFromArray:a];
        [self createCollectionView];
    }path:self.kid];
}

- (void)topConnection
{
    NSDictionary *dic = @{@"id":self.kid};
   [AsyncConnection asyncConnection:REGION_TOP parmaters:dic block:^(NSData *data) {
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       self.topArr = [[dic objectForKey:@"data"]objectForKey:@"items"];
       [self beginConnection];
   }path:[@"mainregion_top" stringByAppendingString:self.kid]];
}

- (void)createCollectionView
{
    NomalPullLayout *flow = [[NomalPullLayout alloc]init];
    flow.layoutArr = self.array;
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:flow];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self.collection registerClass:[ImageColl class] forCellWithReuseIdentifier:@"coll"];
    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"123"];
    self.collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collection];
    [self.collection release];
    [self addFooter];
    
    
}

- (void)addFooter
{
    
    __block RegionViewController *actionVC = self;
    
    [self.collection addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSDictionary *dic = @{@"asc":@"",
                                  @"flag":[NSString stringWithFormat:@"%d", k],
                                  @"id":self.kid,
                                  @"sort":@"all",
                                  @"query":self.name,
                                  @"cat":@"全部",
                                  @"asc":@""};
            [AsyncConnection asyncConnection:REGION_KOREAN parmaters:dic block:^(NSData *data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSArray *arr =[[dic objectForKey:@"data"]objectForKey:@"items"];
                [self.array addObjectsFromArray:arr];
                [self.collection reloadData];
                k += 18;
            }path:self.kid];
            [actionVC.collection footerEndRefreshing];
            
        });
    }];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else{
    return self.array.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"123" forIndexPath:indexPath];
        
        UIImageView *ima = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250 * _offHeigt)];
        
        [ima sd_setImageWithURL:[NSURL URLWithString:[[[self.topArr objectAtIndex:0]objectForKey:@"component"]objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        
        [self.collection addSubview:ima];

        return cell;
    }
    else{
    ImageColl *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"coll" forIndexPath:indexPath];
    
    NSString *pic = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"picUrl"];
    NSArray *arr = [pic componentsSeparatedByString:@"?"];
    
    
    [cell.image sd_setImageWithURL:[NSURL URLWithString:[arr objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    NSDictionary *dic = [[self.array objectAtIndex:indexPath.item]objectForKey:@"component"];
    cell.title.text = [dic objectForKey:@"description"];
    cell.price.text = [@"￥" stringByAppendingString:[dic objectForKey:@"price"]];

    [cell.source sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"nationalFlag"]] forState:UIControlStateNormal];
    [cell.source setTitle:[dic objectForKey:@"country"] forState:UIControlStateNormal];
    return cell;
    }
}




- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
    SpecailWebViewController *speacial = [[SpecailWebViewController alloc]init];
    speacial.name = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"country"];
    speacial.imageUrl = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"nationalFlag"];
    speacial.desc = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"description"];
    speacial.wid = [[[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"action"]objectForKey:@"sourceId"];
    speacial.height = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"height"]floatValue];
    speacial.width = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"width"]floatValue];
    speacial.dic = [[self.array objectAtIndex:indexPath.item]objectForKey:@"component"];
    [self.navigationController pushViewController:speacial animated:YES];
    [speacial release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
